import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/providers/app_providers.dart';
import '../../core/types/app_types.dart';

/**
 * 笔记列表组件
 * 显示当前文件夹或搜索结果的笔记列表
 */
class NoteList extends ConsumerWidget {
  const NoteList({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final currentFolderId = ref.watch(currentFolderProvider);
    final searchQuery = ref.watch(searchQueryProvider);
    final currentNote = ref.watch(currentNoteProvider);

    // 根据搜索状态决定显示哪个列表
    final notesProvider = searchQuery.isNotEmpty
        ? searchResultsProvider
        : notesByFolderProvider(currentFolderId);

    final notesAsync = ref.watch(notesProvider);

    return Container(
      decoration: BoxDecoration(
        color: Theme.of(context).scaffoldBackgroundColor,
        border: Border(
          right: BorderSide(
            color: Theme.of(context).dividerColor,
          ),
        ),
      ),
      child: Column(
        children: [
          // 标题栏
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Theme.of(context).dividerColor,
                ),
              ),
            ),
            child: Row(
              children: [
                Text(
                  searchQuery.isNotEmpty ? '搜索结果' : _getFolderTitle(currentFolderId),
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                const Spacer(),
                if (searchQuery.isEmpty)
                  IconButton(
                    onPressed: () {
                      _createNewNote(ref, currentFolderId);
                    },
                    icon: const Icon(Icons.add),
                    tooltip: '新建笔记',
                  ),
              ],
            ),
          ),

          // 笔记列表
          Expanded(
            child: notesAsync.when(
              data: (notes) {
                if (notes.isEmpty) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          searchQuery.isNotEmpty ? Icons.search_off : Icons.note_outlined,
                          size: 64,
                          color: Theme.of(context).disabledColor,
                        ),
                        const SizedBox(height: 16),
                        Text(
                          searchQuery.isNotEmpty ? '没有找到相关笔记' : '暂无笔记',
                          style: TextStyle(
                            color: Theme.of(context).disabledColor,
                            fontSize: 16,
                          ),
                        ),
                        if (searchQuery.isEmpty) ...[
                          const SizedBox(height: 8),
                          ElevatedButton.icon(
                            onPressed: () {
                              _createNewNote(ref, currentFolderId);
                            },
                            icon: const Icon(Icons.add),
                            label: const Text('创建第一篇笔记'),
                          ),
                        ],
                      ],
                    ),
                  );
                }

                return ListView.builder(
                  padding: const EdgeInsets.all(8),
                  itemCount: notes.length,
                  itemBuilder: (context, index) {
                    final note = notes[index];
                    final isSelected = currentNote?.id == note.id;

                    return _NoteItem(
                      note: note,
                      isSelected: isSelected,
                      onTap: () {
                        ref.read(currentNoteProvider.notifier).setNote(note);
                      },
                      onDelete: () {
                        _showDeleteNoteDialog(context, ref, note);
                      },
                    );
                  },
                );
              },
              loading: () => const Center(child: CircularProgressIndicator()),
              error: (error, stack) => Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.error_outline,
                      size: 64,
                      color: Theme.of(context).colorScheme.error,
                    ),
                    const SizedBox(height: 16),
                    Text(
                      '加载笔记失败',
                      style: TextStyle(
                        color: Theme.of(context).colorScheme.error,
                        fontSize: 16,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      error.toString(),
                      style: TextStyle(
                        color: Theme.of(context).disabledColor,
                        fontSize: 12,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /**
   * 获取文件夹标题
   */
  String _getFolderTitle(int folderId) {
    switch (folderId) {
      case 1:
        return '全部笔记';
      case 2:
        return '未分类';
      default:
        return '笔记';
    }
  }

  /**
   * 创建新笔记
   */
  void _createNewNote(WidgetRef ref, int currentFolderId) async {
    try {
      final folderId = currentFolderId == 1 ? 2 : currentFolderId; // 如果是"全部笔记"，则创建到"未分类"
      
      final note = await ref.read(appDataNotifierProvider.notifier).createNote(
        title: '新笔记',
        content: '',
        folderId: folderId,
      );
      
      // 选中新创建的笔记
      ref.read(currentNoteProvider.notifier).setNote(note);
    } catch (e) {
      // 错误处理由调用方处理
      rethrow;
    }
  }

  /**
   * 显示删除笔记确认对话框
   */
  void _showDeleteNoteDialog(BuildContext context, WidgetRef ref, Note note) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除笔记'),
        content: Text('确定要删除笔记"${note.title}"吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              try {
                await ref.read(appDataNotifierProvider.notifier).deleteNote(note.id);
                
                // 如果删除的是当前选中的笔记，清除选中状态
                final currentNote = ref.read(currentNoteProvider);
                if (currentNote?.id == note.id) {
                  ref.read(currentNoteProvider.notifier).clearNote();
                }
                
                if (context.mounted) {
                  Navigator.of(context).pop();
                }
              } catch (e) {
                if (context.mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('删除笔记失败: $e')),
                  );
                }
              }
            },
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }
}

/**
 * 笔记项组件
 */
class _NoteItem extends StatelessWidget {
  final Note note;
  final bool isSelected;
  final VoidCallback onTap;
  final VoidCallback onDelete;

  const _NoteItem({
    required this.note,
    required this.isSelected,
    required this.onTap,
    required this.onDelete,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 2),
      decoration: BoxDecoration(
        color: isSelected
            ? Theme.of(context).primaryColor.withOpacity(0.1)
            : null,
        borderRadius: BorderRadius.circular(8),
        border: isSelected
            ? Border.all(
                color: Theme.of(context).primaryColor.withOpacity(0.3),
              )
            : null,
      ),
      child: ListTile(
        title: Text(
          note.title.isEmpty ? '无标题' : note.title,
          style: TextStyle(
            fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
            color: note.title.isEmpty
                ? Theme.of(context).disabledColor
                : (isSelected ? Theme.of(context).primaryColor : null),
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (note.content.isNotEmpty) ...[
              const SizedBox(height: 4),
              Text(
                note.content,
                style: TextStyle(
                  fontSize: 12,
                  color: Theme.of(context).textTheme.bodySmall?.color,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ],
            const SizedBox(height: 4),
            Row(
              children: [
                Text(
                  _formatDate(note.updatedAt),
                  style: TextStyle(
                    fontSize: 11,
                    color: Theme.of(context).textTheme.bodySmall?.color,
                  ),
                ),
                const Spacer(),
                if (note.syncStatus != SyncStatus.synced)
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: _getSyncStatusColor(note.syncStatus).withOpacity(0.1),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      _getSyncStatusText(note.syncStatus),
                      style: TextStyle(
                        fontSize: 10,
                        color: _getSyncStatusColor(note.syncStatus),
                      ),
                    ),
                  ),
              ],
            ),
          ],
        ),
        trailing: PopupMenuButton<String>(
          icon: const Icon(Icons.more_vert, size: 16),
          itemBuilder: (context) => [
            const PopupMenuItem(
              value: 'delete',
              child: Row(
                children: [
                  Icon(Icons.delete, size: 16),
                  SizedBox(width: 8),
                  Text('删除'),
                ],
              ),
            ),
          ],
          onSelected: (value) {
            if (value == 'delete') {
              onDelete();
            }
          },
        ),
        onTap: onTap,
        contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      ),
    );
  }

  /**
   * 格式化日期
   */
  String _formatDate(DateTime date) {
    final now = DateTime.now();
    final difference = now.difference(date);

    if (difference.inDays == 0) {
      return '${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
    } else if (difference.inDays == 1) {
      return '昨天';
    } else if (difference.inDays < 7) {
      return '${difference.inDays}天前';
    } else {
      return '${date.month}/${date.day}';
    }
  }

  /**
   * 获取同步状态颜色
   */
  Color _getSyncStatusColor(SyncStatus status) {
    switch (status) {
      case SyncStatus.local:
        return Colors.blue;
      case SyncStatus.pending:
        return Colors.orange;
      case SyncStatus.syncing:
        return Colors.purple;
      case SyncStatus.synced:
        return Colors.green;
      case SyncStatus.error:
        return Colors.red;
    }
  }

  /**
   * 获取同步状态文本
   */
  String _getSyncStatusText(SyncStatus status) {
    switch (status) {
      case SyncStatus.local:
        return '本地';
      case SyncStatus.pending:
        return '待同步';
      case SyncStatus.syncing:
        return '同步中';
      case SyncStatus.synced:
        return '已同步';
      case SyncStatus.error:
        return '错误';
    }
  }
}